(() => {
	const CONF_CATEGORY_EXPAND_STATUS = 'category_expand_status';
	
	let ZTree = $.fn.zTree;
	let leftZTreeObj = null;
	
	let setting = {
		view: {
			showLine: true,
			selectedMulti: false,
			expandSpeed: 120,
		},
		
		data: {
			keep: {
				parent:true
			},
			simpleData: {
				enable: true
			}
		},
		
		callback: {
			beforeCollapse:beforeCollapse,
			onClick:onClick,
			onRightClick:onRightClick,
			beforeRename:beforeRename,
			beforeRemove:beforeRemove,
			onExpand:onExpand,
			onCollapse:onCollapse,
			onDblClick:onDblClick,
			onMouseUp:onCheck,

			beforeDrag: beforeDrag,
			beforeDrop: beforeDrop,
		},
		
		edit: {
			drag: {
				isMove:true,
				isCopy:false,
				autoExpandTrigger: false,
			},
			editNameSelectAll:true,
			enable:true,
			showRemoveBtn:false,
			showRenameBtn:false
		}
	};
	
	function beforeCollapse(id, node) {
		if(node.id === null) {
			return false;
		}
		
		return !(!node.children || node.children.length == 0);
	}
	
	function onExpand(e, id, node) {
		expandEmptyNode(node);
		
		if(!window.SearchController || !SearchController.isInSearch()) {
			_saveCategoryExtendStatus();
		}
	}
	
	function onCollapse() {
		if(!window.SearchController || !SearchController.isInSearch()) {
			_saveCategoryExtendStatus();
		}
	}
	
	/**
	 * 移动位置
	 * @param treeId
	 * @param treeNodes
	 * @param targetNode
	 * @param moveType
	 * @returns {boolean}
	 */
	function beforeDrop(treeId, treeNodes, targetNode, moveType) {
		let node = treeNodes[0];
		
		if(moveType == 'inner') {
			if(!targetNode.isParent) {
				return false;
			}
		} else if(targetNode.id === null) {
			return false;
		}
		
		if(!node.isParent && targetNode.isParent) {
			let lastCateogryNode = _getLastCategory(targetNode.getParentNode());
			
			if(lastCateogryNode.tId != targetNode.tId) {
				if(lastCateogryNode) {
					leftZTreeObj.moveNode(lastCateogryNode, node, 'next', false);
					beforeDrop(node.tId, [node], lastCateogryNode, 'next');
					return false;
				}
			}
		}
		
		let model = null;
		
		if(node.isParent) {
			model = new CategoryModel;
		} else {
			model = new PageModel;
		}
		
		let dataId = _getDataIdFromNode(node);
		
		if(moveType != 'inner') {
			let parentNode = targetNode.getParentNode();
			let brothers = parentNode.children;
			let index = 1;
			let nodeIndex = 0;
			
			for(let i=0; i<brothers.length; i++) {
				let brotherNode = brothers[i];
				
				if(brotherNode.id == -1) {
					continue;
				}
				
				if(brotherNode.tId == node.tId) {
					continue;
				}
				
				if(brotherNode.tId == targetNode.tId) {
					if(moveType == 'prev') {
						nodeIndex = index-1;
					} else {
						nodeIndex = index+1;
					}
				}
				
				let bromodel = _getNodeModel(brotherNode);
				bromodel.setId(_getDataIdFromNode(brotherNode)).setPosition(index).save();
				
				if(!bromodel.ok()) {
					CoreHelper.alertError('保存失败!');
					return false;
				}
				
				index += 2;
			}
			
			model.setId(dataId).setParent(_getDataIdFromNode(targetNode.getParentNode())).setPosition(nodeIndex).save();
		} else {
			model.setId(dataId).setParent(_getDataIdFromNode(targetNode)).setPosition(999999).save();
		}
		
		return true;
	}
	
	function _getNodeModel(node) {
		if(node.isParent) {
			return new CategoryModel;
		} else {
			return new PageModel;
		}
	}
	
	function beforeDrag(treeId, treeNodes) {
		return treeNodes[0].id != null;
	}
	
	/**
	 * 右键操作
	 * @param e
	 * @param id
	 * @param node
	 * @returns {boolean}
	 */
	function onRightClick(e, id, node) {
		if(!node) {
			return false;
		}
		
		e.preventDefault(0);
		let menu = new nw.Menu();
		
		if(node.isParent) {
			
			menu.append(new nw.MenuItem({
				label: '添加目录', click: function () {
					let newNodes =  leftZTreeObj.addNodes(node, '-1', {name: _getCreateName('新建目录', true), id: -1, isParent: true});
					leftZTreeObj.editName(newNodes[0]);
				}
			}));
			
			menu.append(new nw.MenuItem({
				label: '添加页面', click: function () {
					let newNodes =  leftZTreeObj.addNodes(node, '-1', {name:  _getCreateName('新建页面'), id: -1});
					leftZTreeObj.editName(newNodes[0]);
				}
			}));
		} else {
			menu.append(new nw.MenuItem({
				label: '打开', click: function () {
					PageHelper.view(_getDataIdFromNode(node));
				}
			}));
		}
		
		if(node.id !== null) {
			menu.append(new nw.MenuItem({
				label: '重命名', click: function () {
					leftZTreeObj.editName(node);
				}
			}));
			
			menu.append(new nw.MenuItem({
				label: '删除', click: function () {
					leftZTreeObj.removeNode(node, true);
				}
			}));
		}
		
		menu.popup(e.originalEvent.x, e.originalEvent.y);
		leftZTreeObj.selectNode(node, true);
		return false;
	}
	
	function onClick(e, id, node) {
		if(node.id && node.isParent) {
			leftZTreeObj.expandNode(node, !node.open, false, true, true);
		}
		
		if(!node.isParent) {
			PageHelper.view(_getDataIdFromNode(node));
		}
	}
	
	function onCheck(e, tid, node) {
		if(!node) {
			$('#tree_id').html('');
			return;
		}
		
		let id = _getDataIdFromNode(node);
		
		if(id == null) {
			$('#tree_id').html('');
			return;
		}
		
		if(node.isParent) {
			$('#tree_id').html(`目录ID:${id}`);
		} else {
			$('#tree_id').html(`页面ID:${id}`);
		}
	}
	
	function beforeRename(id, node, newName, isCancel) {
		let type="目录";
		let model = null;
		
		if(isCancel) {
			return true;
		}
		
		let dataId = node.id;
		
		leftZTreeObj.cancelEditName();
		
		if(!dataId) {
			CoreHelper.alertError(`此${type}无法保存`);
			return false;
		}
		
		if(node.isParent) {
			model = new CategoryModel();
		} else {
			type="页面";
			
			if(dataId != -1) {
				dataId = String(dataId).substr(1);
			}
			
			model = new PageModel();
		}
		
		if(dataId == -1) {
			if(newName == '') {
				leftZTreeObj.removeNode(node);
				return false;
			}
			
			model.setName(newName)
				.setPosition(999999);
			
			if(node.getParentNode() && node.getParentNode().id) {
				model.setParent(node.getParentNode().id);
			}
			
			if(model.save().getId()) {
				node.id = node.isParent ? model.getId() : `p${model.getId()}`;
			} else {
				CoreHelper.alertError('保存失败:' + model.getError());
				leftZTreeObj.removeNode(node);
				return false;
			}
		} else {
			if(newName == '') {
				CoreHelper.alertError(`名称不能为空`, '我错了');
				return false;
			}
			
			if(!model.load(dataId).getId()) {
				CoreHelper.alertError(`此${type}已不存在`);
				return false;
			} else {
				if(!model.setName(newName).save().ok()) {
					CoreHelper.alertError('保存失败:' + model.getError());
					return false;
				}
			}
		}
		
		return true;
	}
	
	function beforeRemove(id, node) {
		let type="目录";
		let model = null;
		let dataId = node.id;
		
		if(!dataId || dataId == -1) {
			CoreHelper.alertError(`此${type}无法删除`);
			return false;
		}
		
		if(node.isParent) {
			model = new CategoryModel();
			
			if(node.children && node.children.length > 0) {
				CoreHelper.alertError(`目录 '${node.name}' 是一个非空目录不能删除`);
				return false;
			}
		} else {
			type="页面";
			if(dataId != -1) {
				dataId = String(dataId).substr(1);
			}
			model = new PageModel();
		}
		
		if(!confirm(`确定要删除 '${node.name}' 吗?`)) {
			return false;
		}
		
		if(!model.setId(dataId).delete().ok()) {
			CoreHelper.alertError(`删除${type}失败:${model.getError()}`);
			return false;
		}
		
		return true;
	}
	
	function expandEmptyNode(node) {
		if(node.isParent && node.children) {
			let nodes = node.children;
			
			for(let i=0; i<nodes.length; i++) {
				if(nodes[i].isParent) {
					if(!nodes[i].children || nodes[i].children.length == 0) {
						leftZTreeObj.expandNode(nodes[i], true, true, false);
					}
				}
			}
		}
	}
	
	function _getCategoryExtendStatus(nodes) {
		let ids = [];
		
		if(!nodes) {
			nodes = leftZTreeObj.getNodes();
		}
		
		for(let i=0; i<nodes.length; i++) {
			if(nodes[i].open) {
				if(nodes[i].id) {
					ids.push(nodes[i].id);
				}
				
				if(nodes[i].children && nodes[i].children.length > 0) {
					ids = ids.concat(_getCategoryExtendStatus(nodes[i].children))
				}
			}
		}
		
		return ids;
	}
	
	function _saveCategoryExtendStatus() {
		let ary = _getCategoryExtendStatus();
		let str = ary.join(',');
		ConfigModel.saveKeyValue(CONF_CATEGORY_EXPAND_STATUS, str);
	}
	
	
	function onDblClick(e, tid, node) {
		// if(!node || node.isParent) {
		// 	return;
		// }
		//
		// PageHelper.view(_getDataIdFromNode(node));
	}
	
	function _getDataIdFromNode(node) {
		if(node.isParent) {
			return node.id;
		} else {
			if(node.id != -1) {
				return String(node.id).substr(1);
			} else {
				return node.id;
			}
		}
	}
	
	function _getCreateName(name, parent) {
		let allNodes = leftZTreeObj.transformToArray(leftZTreeObj.getNodes());
		let map = {};
		
		for (let i=0; i<allNodes.length; i++) {
			if(parent) {
				if(allNodes[i].isParent) {
					map[allNodes[i].name] = true;
				}
			} else {
				if(!allNodes[i].isParent) {
					map[allNodes[i].name] = true;
				}
			}
		}
		
		let testName = name;
		let testCount = 0;
		let index = 1;
		
		while(map[testName]) {
			testName = `${name} (${index})`;
			index++;
			testCount++;
			
			if(testCount >= 1000) {
				let time = Core.date('Ymd_His');
				return `${name} (${time})`;
			}
		}
		
		return testName;
	}
	
	window.LeftTree = {};
	LeftTree.render = function (data) {
		if(LeftTree.ztree) {
			LeftTree.ztree.destroy();
		}
		
		LeftTree.ztree = ZTree.init(LeftTree.elm, LeftTree.setting,
			[{
				name:'根目录',
				id:null,
				open:true,
				isParent:true
			}].concat(data.map((row) => {
				if(categoryExpandStatus.indexOf(row.id) !== -1) {
					row.open = true;
				}
				
				return row;
			}))
		);
		
		let lastPageId = PageHelper.getLastPageId();
		
		if(lastPageId) {
			let lastPageNode = LeftTree.ztree.getNodeByParam('id', CategoryHelper.getPageTreeId(lastPageId));
			let node = null;
			
			if(lastPageNode) {
				if(window.SearchController && SearchController.isInSearch() && SearchController.isSearchAll()) {
					if(SearchController.isMatchPage(lastPageNode.origin_id)) {
						node = lastPageNode;
					}
				} else {
					node = lastPageNode;
				}
			}
			
			if(!node) {
				let allNodes = LeftTree.ztree.getNodesByParam('isParent', false);
				
				if(allNodes && allNodes.length > 0) {
					node = allNodes[0];
				}
			}
			
			if(node) {
				let tid = node.tId;
				
				if(tid) {
					$('#' + tid + '_a').click();
				}
			} else {
				$('#page_content').html($('#empty_search_tip').html());
			}
		}
		
		if(window.SearchController && SearchController.isInSearch()) {
			LeftTree.ztree.expandAll(true);
			let root = LeftTree.ztree.getNodesByParam('id', null);
			_removeEmptyDirectory(root[0]);
		}
		
		
		return LeftTree.ztree;
	};
	
	function _removeEmptyDirectory(node) {
		let children = node.children;
		children = children ? children : [];
		let childrenLen = children.length;
		let hide = 0;
		
		for(let i=0; i<childrenLen; i++) {
			if(children[i].isParent) {
				if(!children[i].children || children[i].children.length == 0) {
					LeftTree.ztree.hideNode(children[i]);
					hide++;
				} else {
					if(_removeEmptyDirectory(children[i])) {
						hide++;
					}
				}
			}
		}
		
		if(hide == childrenLen) {
			if(node.id !== null) {
				LeftTree.ztree.hideNode(node);
				return true;
			}
		}
		
		return false;
	}
	
	let categoryExpandStatus = ConfigModel.getKeyValue(CONF_CATEGORY_EXPAND_STATUS, '');
	categoryExpandStatus.split(',');
	
	
	LeftTree.setting = setting;
	LeftTree.elm = CoreHelper.CategorySidebarElement;
	
	leftZTreeObj = LeftTree.render(CategoryHelper.getTreeData());
	
	function _getLastCategory(node) {
		let lastNode = null;
		
		if(node.isParent && node.children) {
			let children = node.children;
			
			for(let i=0; i<children.length; i++) {
				if(children[i].isParent) {
					lastNode = children[i];
				}
			}
		}
		
		return lastNode;
	}
	
	expandEmptyNode(leftZTreeObj.getNodes()[0]);
})();
